/************************************************************
 *  * EaseMob CONFIDENTIAL
 * __________________
 * Copyright (C) 2013-2014 EaseMob Technologies. All rights reserved.
 *
 * NOTICE: All information contained herein is, and remains
 * the property of EaseMob Technologies.
 * Dissemination of this information or reproduction of this material
 * is strictly forbidden unless prior written permission is obtained
 * from EaseMob Technologies.
 */

#import "LoginViewController.h"
#import "Utils.h"
#import "SYVerifyLoginViewController.h"

@interface LoginViewController ()<UITextFieldDelegate,UIAlertViewDelegate>

@property (strong, nonatomic) IBOutlet UITextField *usernameTextField;
@property (strong, nonatomic) IBOutlet UITextField *passwordTextField;
@property (strong, nonatomic) IBOutlet UIButton *loginButton;
@property (strong, nonatomic) IBOutlet UIView *passwordBackground;
@property (strong, nonatomic) IBOutlet UIView *acountBackground;

@property (strong, nonatomic) IBOutlet UISwitch *useIpSwitch;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *appicon_top;

- (IBAction)forgetPassword:(id)sender;
- (IBAction)doLogin:(id)sender;


@end

@implementation LoginViewController{
    
    BOOL needChangeRootViewController;
}

@synthesize usernameTextField = _usernameTextField;
@synthesize passwordTextField = _passwordTextField;
@synthesize loginButton = _loginButton;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
        
    }
    return self;
}


- (void)viewSetCornerRadius:(UIView *)view{
    view.layer.cornerRadius = 4.0f;
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    
    if (IPHONEX) {
        
        _appicon_top.constant = 124;
    }else{
        _appicon_top.constant = 94;
    }
    self.IdArray=[[NSMutableArray alloc]init];
    self.contactsSource=[NSMutableArray array];
    [self viewSetCornerRadius:_loginButton];
    
    [self viewSetCornerRadius:_passwordBackground];
    [self viewSetCornerRadius:_acountBackground];
    
    self.nameDic=[NSDictionary dictionary];
    
    [self setupForDismissKeyboard];
    _usernameTextField.delegate = self;
    _usernameTextField.placeholder = @"师云号或手机号";
    _passwordTextField.delegate = self;
    _passwordTextField.tintColor = [UIColor blueColor]; //设置光标的颜色
    
    //添加内容改变的监听
    [_passwordTextField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    NSString *username = [self lastLoginUsername];
    if (username && username.length > 0) {
        _usernameTextField.text = username;
    }
    
    self.title = @"登录";
    
    _usernameTextField.delegate=self;
    [_usernameTextField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    
    NSUserDefaults *ud=[NSUserDefaults standardUserDefaults];
    if ([ud objectForKey:@"sound"]==nil||[ud objectForKey:@"zhendong"]==nil) {
        [ud setObject:@"no" forKey:@"noMessage"];
        [ud setObject:@"yes" forKey:@"sound"];
        [ud setObject:@"yes" forKey:@"zhendong"];
        [ud synchronize];
    }
    
    NSDictionary *dic;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(doLogin:) name:@"SY_verifyDoLogin" object:dic];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(registerScuess:) name:@"registerScuess" object:nil];
}


-(void)registerScuess:(NSNotification *)noti{
    
    
    NSDictionary *dic = noti.object;
    
    NSString *loginName = [dic objectForKey:@"phone"];
    
    NSString *loginPass = [dic objectForKey:@"password"];
    
    self.usernameTextField.text = loginName;
    self.passwordTextField.text = loginPass;
    
    
    self.loginButton.enabled = YES;
    self.loginButton.backgroundColor = [UIColor colorWithHexString:@"#1ebfff"];
    
    //直接登录
    [self doLogin:nil];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


//注册账号
- (IBAction)doRegister:(id)sender {
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
    UIViewController * view = [storyboard instantiateViewControllerWithIdentifier:@"RegisteViewController"];
    [self.navigationController pushViewController:view animated:YES];
    
}

//

//弹出提示的代理方法
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if ([alertView cancelButtonIndex] != buttonIndex) {
        
        UITextField *nameTextField = [alertView textFieldAtIndex:0];
        if(nameTextField.text.length > 0)
        {
            
        }
    }
    //登陆
    [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_LOGINCHANGE object:@YES];
}

#pragma mark -忘记密码
- (IBAction)forgetPassword:(id)sender {
    
    SYVerifyLoginViewController *verifyVC = [[SYVerifyLoginViewController alloc] initWithNibName:@"SYVerifyLoginViewController" bundle:nil];
    [self.navigationController pushViewController:verifyVC animated:YES];
    

}

#pragma mark -登录点击事件
- (IBAction)doLogin:(id)sender {
    
    if ([sender isKindOfClass:[NSNotification class]]) {
        NSLog(@"%@",sender);
        
        NSDictionary *dic = [sender valueForKeyPath:@"object"];
        
        self.usernameTextField.text = [dic objectForKey:@"_phoneNum"];
        self.passwordTextField.text = [dic objectForKey:@"newpass"];
    }
    
    if (![self isEmpty]) {
        [self.view endEditing:YES];
        
        //支持是否为中文
        if ([self.usernameTextField.text isChinese]) {
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:NSLocalizedString(@"login.nameNotSupportZh", @"Name does not support Chinese")
                                  message:nil
                                  delegate:nil
                                  cancelButtonTitle:NSLocalizedString(@"ok", @"OK")
                                  otherButtonTitles:nil];
            
            [alert show];
            
            return;
        }
        
        
        NSMutableDictionary * dict = [[NSMutableDictionary alloc] initWithCapacity:0];
        [dict setObject:@"api_user_login" forKey:@"method"];
        [dict setObject:self.usernameTextField.text forKey:@"loginname"];
        
        NSString * finalPassWord = [Utils MD5EncryptWith:self.passwordTextField.text];
        [dict setObject:finalPassWord forKey:@"userpass"];
        
        [Utils getWithparameters:dict showHUD:YES success:^(NSInteger recode, id resposeJson) {
            
            //充值解题密码状态
            [SYAccountTool ShareAccount].hasInputpwd = NO;
            
            NSLog(@"---%@--LOGIN",resposeJson);
            NSDictionary * dict = (NSDictionary *)resposeJson;
            NSDictionary *redataDic=[dict objectForKey:@"re_data"];
            int firstlogin = [[redataDic objectForKey:@"firstlogin"] intValue];
            
            /*如果是首次登陆的话，需要存到userdefaults里面,在mainViewController里用*/
            if (firstlogin == 1) {
                
                [[NSUserDefaults standardUserDefaults] setInteger:firstlogin forKey:SYISFirstLogin];
                [[NSUserDefaults standardUserDefaults] synchronize];
            }
            [self saveLastLoginUsername];
            
            NSMutableDictionary * personalImformation = [dict objectForKey:@"re_data"];
            
            if (personalImformation.count>0) {
                NSDictionary * userinfo = [personalImformation objectForKey:@"userinfo"];
                
                /*判断是否需要重新初始化sycontractstool单例类，对比两个userid，不一样说明换用户登录，需要从新初始化单例类，从新创建数据库,并且清理webview缓存*/
                [self refreshUserInfo:userinfo];
                
                //储存用户数据
                [self saveUserDataWithResposeData:personalImformation];
                
                //登录成功绑定用于推送的chinnelid
                AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
                [delegate bindChinnelId];
            }
            
        } failure:^(NSInteger recode, NSError *error) {
            [self showHint:@"网络异常，请稍后重试！"];
        }];
        
    }
}


- (void)refreshUserInfo:(NSDictionary *)userinfo{
    
    NSString *curUserid = [NSString stringWithFormat:@"%@",[userinfo objectForKey:@"userid"]];
    
    //获取上一次存的userid
    NSString *oriUserid = [[NSUserDefaults standardUserDefaults] objectForKey:@"oriuserid"];
    
    [[NSUserDefaults standardUserDefaults] setObject:curUserid forKey:@"oriuserid"];
    
    if (oriUserid) {
        
        if (![curUserid isEqualToString:oriUserid]) {
            
            [[NSUserDefaults standardUserDefaults] setDouble:0 forKey:updateKey];
            
            [[NSUserDefaults standardUserDefaults] synchronize];
            
            /*从新登录，清理webview缓存*/
            [Utils clearWebViewCache];
            
        }
    }
}


//保存用户数据
- (void)saveUserDataWithResposeData:(NSMutableDictionary *)personalImformation
{
    
    BOOL save = [SyUserInfomation personalImformationSaveWtih:personalImformation];
    NSLog(@"save status 1 is success 0 is failture :%i",save);
    NSDictionary * userinfo = [personalImformation objectForKey:@"userinfo"];
    
    NSString * userID = [NSString stringWithFormat:@"%@",[userinfo objectForKey:@"userid"]];
    NSString * token = [NSString stringWithFormat:@"%@",[userinfo objectForKey:@"token"]];
    //手机号 mobile
    NSString *mobile = [userinfo objectForKey:@"mobile"];
    //头像 logo
    NSString *logo = [userinfo objectForKey:@"logo"];
    
    
    NSUserDefaults * UD = [NSUserDefaults standardUserDefaults];
    [UD setObject:mobile forKey:@"mobile"]; //手机号
    [UD setObject:userID forKey:@"userid"]; //userid
    [UD setObject:token forKey:@"token"];
    [UD setObject:logo forKey:XZHEADURL];
    [UD setObject:@"1" forKey:@"isLogin"];
    
    [UD synchronize];

    [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_LOGINCHANGE object:@YES];
    
    //重新建表
    //[fmdbTool initialize];
}

- (BOOL)isEmpty{
    BOOL ret = NO;
    NSString *username = _usernameTextField.text;
    NSString *password = _passwordTextField.text;
    if (username.length == 0 || password.length == 0) {
        ret = YES;
    }
    
    return ret;
}


#pragma  mark - TextFieldDelegate
-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    if (textField == _usernameTextField) {
        _passwordTextField.text = @"";
        _loginButton.enabled = NO;
        [_loginButton setBackgroundColor:[UIColor colorWithHexString:@"#fccaca"]];
    }
    
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if (textField == _usernameTextField) {
        [_usernameTextField resignFirstResponder];
        [_passwordTextField becomeFirstResponder];
    } else if (textField == _passwordTextField) {
        [_passwordTextField resignFirstResponder];
        [self doLogin:nil];
    }
    return YES;
}


#pragma  mark - private
- (void)saveLastLoginUsername
{
    
    NSString *username=_usernameTextField.text;
    if (username && username.length > 0) {
        NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
        [ud setObject:username forKey:[NSString stringWithFormat:@"em_lastLogin_%@",kSDKUsername]];
        [ud setObject:self.nameDic forKey:@"user_names"];
        [ud synchronize];
    }
    
}


- (NSString*)lastLoginUsername
{
    NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
    NSString *username = [ud objectForKey:[NSString stringWithFormat:@"em_lastLogin_%@",kSDKUsername]];
    if (username && username.length > 0) {
        return username;
    }
    
    return nil;
}



#pragma mark - private
- (void)textFieldDidChange:(UITextField *)textField
{
    if (textField == _usernameTextField) {
        if (textField.text.length > 11) {
            textField.text = [textField.text substringToIndex:11];
        }
    }
    
    if (textField==_passwordTextField)
    {
        if (_passwordTextField.text.length > 16) {
            UITextRange *markedRange = [_passwordTextField markedTextRange];
            if (markedRange) {
                return;
            }
            //Emoji占2个字符，如果是超出了半个Emoji，用15位置来截取会出现Emoji截为2半
            //超出最大长度的那个字符序列(Emoji算一个字符序列)的range
            NSRange range = [_passwordTextField.text rangeOfComposedCharacterSequenceAtIndex:16];
            _passwordTextField.text = [_passwordTextField.text substringToIndex:range.location];
        }
    }

    
    if (_usernameTextField.text.length > 0 && _passwordTextField.text.length >= 6 && _passwordTextField.text.length<=16) {
        
        _loginButton.enabled = YES;
        [_loginButton setBackgroundColor:[UIColor colorWithHexString:@"#fb524a"]];
        
    }else{
        
        _loginButton.enabled = NO;
        [_loginButton setBackgroundColor:[UIColor colorWithHexString:@"#fccaca"]];
    }
}



@end
